<?php
/**
 * 旅行社栏目
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/18 0018
 * Time: 16:51
 */
namespace App\Http\Controllers;
use App\Http\Requests\StoreRequest;
use App\Models\Agency;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AgencyMenuController extends BaseController{
    //菜单列表
    public function index()
    {

       $menu = DB::table('tour_menu')->where('parent_id','0')->get()->toArray();



       $menu = $this->objectToArray($menu);
       $list = array();
       foreach ($menu as $k=>&$v){

            $chidlren =  DB::table('tour_menu')->where('parent_id',$v['menu_id'])->get()->toArray();
            $chidlren = $this->objectToArray($chidlren);
            if($chidlren) {
                $v['children'] = $chidlren;
            }
           $list[] = $v;

       }
      // print_r($list);
        return view('AgencyMenu.index',['menus'=>$list]);
    }


    public static function toTree($array=[],$parent_id='0',$level= '0'){


}
//编辑或者增加
public function edit($id=0){
        //echo $id;
    if($id == '0') {
        $menus = DB::table('tour_menu')->where('parent_id', '0')->get()->toArray();
        $menus = $this->objectToArray($menus);
        $menu ='';
    }else{
        $menus = DB::table('tour_menu')->get()->toArray();
        $menus = $this->objectToArray($menus);
        $menu =  DB::table('tour_menu')->where('menu_id', $id)->first();

        $menu = $this->objectToArray($menu);
    }
        return view('AgencyMenu.edit',['menus'=>$menus,'menu_id'=>$id,'menu'=>$menu]);
}
public  function  save(StoreRequest $request){
    $arr = $request->all();
    $map['name'] = $arr['name'];
    $map['parent_id'] = $arr['category'];
    $map['menu_img'] = $arr['img'];
    if($arr['id'] == '0'){
        Db::table('tour_menu')->insert($map);
    }else{
        Db::table('tour_menu')->where('menu_id',$arr['id'])->update($map);
    }
    return ['status'=>1,'msg'=>trans('添加成功')];
}

    /**
     * @param $id
     * 删除菜单
     */
public function destroy($id){
    $menu = DB::table('tour_menu')->where('menu_id',$id)->delete();
    return ['status'=>1,'msg'=>trans('删除成功')];
}

/**
 *  对象专数组
 */
function objectToArray($object) {
        //先编码成json字符串，再解码成数组
        return json_decode(json_encode($object), true);
    }

}